package com.quanyan.common.encrypt;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author songzj
 * @date 16/4/18-14:55
 */
public class RSAKeycrypt extends Coder {

    private static String PRIVATE_KEY_DATA = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKoCdwJrYlqLNYZgThveCJawxktz\n" +
            "tvLzToEUBQU9nDS8u7tu8XimcVg07ZcOh5OS4DevE/gfzOxh4DAtuwzAjTQG4JQkmKtYPRdzZJHe\n" +
            "VAwxfj148j9Fu+aG/5xQKRejsr6s5Mz8DsXhKHcutFAd5jq/DereDgd3IeSCoqsBwyBVAgMBAAEC\n" +
            "gYAyEO/DQqSATabBn/Lgug6FciGzbqxd99ESqjagSHiL/1i55f4urbWLaGrfpWO/ze1B+MlEtPjA\n" +
            "VEKVbaI8KyhpwutCvXIMu1CHXF1r/Hj5nxlDClgEqNAfdrr0XtYOojWvvb7RpiIdlobzeslAcOd4\n" +
            "0p1yTZE90OkNbKKSEWPugQJBANp174RooJou/z5bzAIxxkrNBVyoareCQy/94vwO7oxbSUeJHdeX\n" +
            "oel8SgbhHS2ZC0SE+1vn/Xh3v1dOGhAiLB0CQQDHOSwEj58tgtZnllME+ZqGrIWUNa6ORJBp6n81\n" +
            "Fa8ppF2HHxnhZ4uh30v1aUEhHXbdnYJvsNglTh0HdsCJWF+ZAkEAgZo13nezz8TR6EzNWv/sg7Pd\n" +
            "2nqP1Q6SjYYxgxfYrav6bVYLPjvW8o2p3SrwBH0nEh9Sf9PBrBZejYzoKWocgQJBAIOvzuDU7qru\n" +
            "qTqfqxDGzNXohAOL2G5B9BOO5bb5NmeYNhpy/HB6OVoud88oW9y/1Sp4Sxf5FWbTU2zzmiEvQUEC\n" +
            "QQC2qBoRbUp9Jz8xxonZOrszpYbPsDgozcpFcFORH8uI0miofXPCtPObclRk2kBpMNAAOrf1ngNh\n" +
            "xqmvfs9jkDAE\n";

    private static String PUBLIC_KEY_DATA = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqAncCa2JaizWGYE4b3giWsMZLc7by806BFAUF\n" +
            "PZw0vLu7bvF4pnFYNO2XDoeTkuA3rxP4H8zsYeAwLbsMwI00BuCUJJirWD0Xc2SR3lQMMX49ePI/\n" +
            "Rbvmhv+cUCkXo7K+rOTM/A7F4Sh3LrRQHeY6vw3q3g4HdyHkgqKrAcMgVQIDAQAB\n";


    /**
     * 私钥加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data) throws Exception {
        return cryptByPrivateKey(data, Cipher.ENCRYPT_MODE);
    }

    /**
     * 私钥加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(String data) throws Exception {
        return encryptByPrivateKey(data.getBytes(UTF_8));
    }

    /**
     * 私钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data) throws Exception {
        return cryptByPrivateKey(data, Cipher.DECRYPT_MODE);
    }

    /**
     * 私钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data) throws Exception {
        return decryptByPrivateKey(data.getBytes(UTF_8));
    }

    /**
     * 公钥加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data) throws Exception {
        return cryptByPublicKey(data, Cipher.ENCRYPT_MODE);
    }


    /**
     * 公钥加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data) throws Exception {
        return encryptByPublicKey(data.getBytes(UTF_8));
    }


    /**
     * 公钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data) throws Exception {
        return cryptByPublicKey(data, Cipher.DECRYPT_MODE);
    }

    /**
     * 公钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(String data) throws Exception {
        return decryptByPublicKey(data.getBytes(UTF_8));
    }


    /**
     * 公钥加密解密
     *
     * @param data
     * @param cryptMode
     * @return
     * @throws Exception
     */
    private static byte[] cryptByPublicKey(byte[] data, int cryptMode) throws Exception {
        Key publicKey = getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(cryptMode, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 私钥加密解密
     *
     * @param data
     * @param cryptMode
     * @return
     * @throws Exception
     */
    private static byte[] cryptByPrivateKey(byte[] data, int cryptMode) throws Exception {
        Key privateKey = getPrivateKey();
        Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        cipher.init(cryptMode, privateKey); //加密解密模式
        return cipher.doFinal(data);
    }


    /**
     * 私钥签名
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data) throws Exception {
        PrivateKey privateKey = getPrivateKey();
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    /**
     * 使用公钥验证签名
     *
     * @param data
     * @param sign
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, String sign) throws Exception {
        PublicKey publicKey = getPublicKey();
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(decryptBASE64(sign));
    }


    /**
     * 获取公钥
     *
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKey() throws Exception {
        byte[] keyBytes = decryptBASE64(PUBLIC_KEY_DATA); //获取公钥并解密.
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);
        return keyFactory.generatePublic(x509EncodedKeySpec);
    }

    /**
     * 获取私钥
     *
     * @return
     * @throws Exception
     */
    private static PrivateKey getPrivateKey() throws Exception {
        byte[] keyBytes = decryptBASE64(PRIVATE_KEY_DATA); //解密秘钥
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);
        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    private static String readKey(String fileName) {
        BufferedReader bufferedReader = null;
        try {
            String path = RSAKeycrypt.class.getClassLoader().getResource(fileName).getPath();
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            return stringBuffer.toString();
        } catch (IOException e) {
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }


}
